package org.linlinjava.litemall.db.service;

import org.linlinjava.litemall.db.dao.LitemallActivityRulesMapper;
import org.linlinjava.litemall.db.domain.LitemallActivityPic;
import org.linlinjava.litemall.db.domain.LitemallActivityRules;
import org.linlinjava.litemall.db.domain.LitemallActivityRulesExample;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class LitemallActivityRulesService {

    @Resource
    private LitemallActivityRulesMapper litemallActivityRulesMapper;

    public List<LitemallActivityRules> findByActivityId(Integer activityId) {
        LitemallActivityRulesExample example = new LitemallActivityRulesExample();
        LitemallActivityRulesExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andDeletedEqualTo(LitemallActivityPic.NOT_DELETED);
        return litemallActivityRulesMapper.selectByExample(example);
    }

    public LitemallActivityRules findByActivityIdAndSubjectId(Integer activityId, Integer subjectId) {
        LitemallActivityRulesExample example = new LitemallActivityRulesExample();
        LitemallActivityRulesExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andIdEqualTo(subjectId);
        criteria.andDeletedEqualTo(LitemallActivityPic.NOT_DELETED);
        return litemallActivityRulesMapper.selectOneByExample(example);
    }

    /**
     * 添加团购活动用户信息
     *
     * @param entity
     */
    public void addActivityRules(LitemallActivityRules entity, LitemallAdmin admin) {
        entity.setCreatedBy(admin.getId().toString());
        entity.setUpdatedBy(admin.getId().toString());
        entity.setAddTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        litemallActivityRulesMapper.insertSelective(entity);
    }

    public int updateById(LitemallActivityRules activity, LitemallAdmin admin) {
        activity.setUpdateTime(LocalDateTime.now());
        activity.setUpdatedBy(admin.getId().toString());
        LitemallActivityRulesExample example = new LitemallActivityRulesExample();
        example.or().andIdEqualTo(activity.getId());
        return litemallActivityRulesMapper.updateByExampleSelective(activity, example);
    }

    public void deleteById(Integer id) {
        litemallActivityRulesMapper.logicalDeleteByPrimaryKey(id);
    }

    public List<LitemallActivityRules> findByParam(List<Map<String, Object>> params) {
        if (CollectionUtils.isEmpty(params)) {
            return Collections.emptyList();
        }
        return litemallActivityRulesMapper.findByParams(params);
    }
}
